<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="never" style="box-shadow: none !important;">
            <div slot="header" class="clearfix">
              <span>个人资料</span>
            </div>
            <div style="display: flex;justify-content: center;">
              <div label="头像上传" @click="dialogVisible = true" style="margin-bottom: 20px;display: inline-block;cursor: pointer;">
                <el-tooltip content="点击上传头像" placement="top">
                  <el-avatar fit="fill" icon="el-icon-user-solid" :src="readHeadUrl" style="width: 120px; height: 120px;"></el-avatar>
                </el-tooltip>
              </div>
            </div>
            <ul class="user-info">
              <li class="flexSpeen">
                <span>登录账号</span>
                <span>{{readForm.username}}</span>
              </li>
              <li class="flexSpeen">
                <span>用户昵称</span>
                <span>{{readForm.truename}}</span>
              </li>
              <li class="flexSpeen">
                <span>所属部门</span>
                <span>{{readForm.deptList.map(item => item.name).join()}}</span>
              </li>
              <li class="flexSpeen">
                <span>所属频道</span>
                <span>{{readForm.channelList.map(channel => channel.name).join()}}</span>
              </li>
              <li class="flexSpeen">
                <span>所属用户组</span>
                <span>{{readForm.rolsInfo.map(roles => roles.name).join()}}</span>
              </li>
              <li class="flexSpeen">
                <span>安全相关</span>
                <span>
                  <el-link type="primary" @click="dialogUpPassVisible = true">修改密码</el-link>
                </span>
              </li>
            </ul>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用户资料" name="first">
              <el-form ref="editFormRef" :rules="editFormRules" :model="editForm" label-width="80px" style="width: 580px;margin-top: 10px;">
                <el-form-item label="昵称">
                  <el-input v-model="editForm.truename"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" size="small" @click="onSubmit">保存</el-button>
                  <el-button size="small" @click="onCancel">取消</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="操作日志" name="second">
              <!-- 列表区域 -->
              <el-table
                size="small"
                ref="table"
                v-loading="loading"
                :data="data"
                border
                stripe
                height="65vh"
                style="width: 100%">
                <el-table-column
                  label="序号"
                  type="index"
                  width="60">
                </el-table-column>
                <!-- <el-table-column type="index" label="序号"></el-table-column> -->
                <el-table-column prop="msg" label="行为"></el-table-column>
                <el-table-column prop="ip" label="ip"></el-table-column>
                <el-table-column prop="create_time" label="创建日期"></el-table-column>
              </el-table>
              <!--分页组件-->
              <el-pagination
                :total="total"
                :current-page="page + 1"
                style="margin-top: 8px;"
                layout="total, prev, pager, next, sizes"
                @size-change="sizeChange"
                @current-change="pageChange"
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
      <el-dialog
        title="头像上传"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="30%">
        <div class="el-upload-list--picture-card">
          <el-upload
            class="avatar-uploader"
            ref="upload"
            auto-upload
            list-type="picture-card"
            :action="editFormUpload"
            :show-file-list="false"
            :disabled="imageUrl !== ''"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <div v-if="imageUrl" style="position: relative;width: 100%;height: 100%;">
              <img
                class="el-upload-list__item-thumbnail avatar"
                :src="imageUrl" alt="" style="height: 120px;"
              >
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <i class="el-icon-download"></i>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove($event)"
                >
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
          </el-upload>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="onSubmitHeadImg">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改密码"
        :visible.sync="dialogUpPassVisible"
        :close-on-click-modal="false"
        @close="passForm = {}"
        width="460px">
        <el-form>
          <el-form size="small" ref="passFormRef" :rules="passFormRules" :model="passForm" label-width="100px" style="width: 360px;margin-top: 10px;">
            <el-form-item label="原始密码" prop="oldpass">
              <el-input type="password" v-model="passForm.oldpass" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newpass">
              <el-input type="password" v-model="passForm.newpass" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="重复新密码" prop="rplpass">
              <el-input type="password" v-model="passForm.rplpass" placeholder="请输入"></el-input>
            </el-form-item>
          </el-form>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogUpPassVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="onSubmitPassUp">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import crud from '@/mixins/crud'
import { mapGetters } from 'vuex'
export default {
  mixins: [crud],
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }

      return callback(new Error('请输入合法的邮箱'))
    }
    // 验证手机号
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        // 合法的手机号
        return callback()
      }

      return callback(new Error('请输入正确的手机号'))
    }
    var validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passForm.rplpass !== '') {
          this.$refs.passFormRef.validateField('rplpass')
        }
        callback()
      }
    }
    // 验证密码是否重复
    var validateRplPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passForm.newpass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // 用户信息表单对象
      editForm: {},
      readForm: { // 左侧表单信息
        deptList: [],
        channelList: [],
        rolsInfo: []
      },
      readHeadUrl: '', // 左侧表单头像地址

      dialogVisible: false, // 头像上传弹窗
      // 用户头像
      imageUrl: '',
      // 头像预览属性
      picPreDialogVisible: false,
      // 用户头像提交路径
      editFormUpload: process.env.VUE_APP_BASE_URL + '/uploadHead/' + this.$localStorage.get('userid'),
      // 活跃标签页
      activeName: 'first',
      // 用户编辑表单信息
      editFormRules: {
        email: [
          { required: true, message: '请输入用户的邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户的手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' } // 自定义手机号校验规则
        ]
      },
      // 密码修改弹窗相关
      dialogUpPassVisible: false,
      passForm: {}, // 密码修改表单对象
      passFormRules: {
        oldpass: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newpass: [
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' },
          { validator: validateNewPass, trigger: 'blur' }
        ],
        rplpass: [
          { min: 6, max: 15, message: '密码的长度在6~15个字符', trigger: 'blur' },
          { validator: validateRplPass, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters({
      token: 'token'
    })
  },
  created() {
    // console.log(type('abc'))
    this.getUserInfo()
  },
  mounted() {
    // console.log(process.env.VUE_APP_BASE_URL)
  },
  inject: ['reload'],
  methods: {
    // 获取用户信息
    async getUserInfo() {
      this.$store.dispatch('GetInfo').then(res => {
        const { id, username, truename, head_img, email, mobile, depart, channel, deptList, channelList, rolsInfo } = res.data.data
        this.editForm = { id, username, truename, head_img, email, mobile, depart, channel }
        this.editForm.deptList = Array.from(deptList)
        this.editForm.channelList = Array.from(channelList)
        this.editForm.rolsInfo = Array.from(rolsInfo)

        this.imageUrl = head_img === '' ? '' : this.$fileserver + head_img
        this.readHeadUrl = head_img === '' ? '' : this.$fileserver + head_img

        this.readForm = JSON.parse(JSON.stringify(this.editForm))
      })
    },
    beforeInit() {
      this.url = 'Log/auth'
      return true
    },
    // 上传文件前的钩子函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 获PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过2MB')
      }

      return isJPG && isLt2M
    },

    // 上次成功时的钩子
    handleAvatarSuccess(response, file, filelist) {
      // console.log(response)
      if (response.meta.status !== 200) {
        return this.$message.error(response.meta.message)
      }
      this.imageUrl = this.$fileserver + response.data[0]
      this.editForm.head_img = response.data[0]
    },

    // 表单提交
    onSubmit() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改用户信息的请求
        const { data: res } = await this.$http.put('usersinfo/' + this.editForm.id, {
          // username: this.editForm.username,
          head_img: this.editForm.head_img,
          truename: this.editForm.truename,
          mobile: this.editForm.mobile,
          email: this.editForm.email
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.message)
        }

        this.$message.success('修改成功')
        this.getUserInfo()
      })
    },
    // 保存头像
    async onSubmitHeadImg() {
      // 发起修改用户信息的请求
      const { data: res } = await this.$http.put('userupheadimg/' + this.editForm.id, {
        head_img: this.editForm.head_img
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }

      this.$message.success('头像上传成功！')
      this.dialogVisible = false
      this.getUserInfo()
      // window.location.reload()
      // this.reload()
    },
    // 取消按钮回调, 返回页面上一个路由
    onCancel() {
      this.$router.back(-1)
    },
    // 移除
    handleRemove(event) {
      this.imageUrl = ''
      this.editForm.head_img = ''
      event.stopPropagation() // 阻止当前移除点击事件触发后继续向上冒泡
    },
    // 下载
    handleDownload() {
      console.log(this.imageUrl)
    },
    // 预览
    handlePictureCardPreview() {
      this.picPreDialogVisible = true
    },
    // 标签页变化
    handleClick(tab, event) {
      if (tab.name === 'second') {
        this.init()
      }
    },
    // 修改密码表单提交
    onSubmitPassUp() {
      this.$refs.passFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('useruppass/' + this.editForm.id, this.passForm)
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.message)
        }

        this.dialogUpPassVisible = false
        return this.$message.success('密码修改成功!')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
}

.user-info {
  padding-left: 0;
  list-style: none;
}
.user-info li {
  border-bottom: 1px solid #f0f3f4;
  padding: 11px 0;
  font-size: 13px;
}
.flexSpeen {
  display: flex;
  justify-content: space-between;
}
</style>
